package com.freight.user.serviceimpl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.freight.core.common.exception.FreightException;
import com.freight.core.common.redis.RedisTemplateHelper;
import com.freight.core.common.utils.ObjectUtil;
import com.freight.core.common.utils.SecurityUtil;
import com.freight.core.common.vo.SearchVo;
import com.freight.core.entity.User;
import com.freight.core.service.UserService;
import com.freight.file.constants.FileConstant;
import com.freight.file.entity.File;
import com.freight.file.service.FileService;
import com.freight.file.util.FileUtils;
import com.freight.file.util.IdCardOCRUtil;
import com.freight.file.util.MyFileUtils;
import com.freight.file.vo.IdCardBackVo;
import com.freight.file.vo.IdCardFaceVo;
import com.freight.file.vo.PicFileVo;
import com.freight.msg.service.MessageService;
import com.freight.user.dao.IdCardDao;
import com.freight.user.entity.*;
import com.freight.user.mapper.CompanyVoMapper;
import com.freight.user.service.CompanyUserService;
import com.freight.user.service.DriverUserService;
import com.freight.user.service.IdCardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.*;
import java.util.*;

/**
 * 身份证接口实现
 *
 * @author huyingtai
 */
@Slf4j
@Service
@Transactional
public class IdCardServiceImpl implements IdCardService {

    @Autowired
    private IdCardDao idCardDao;

    @Autowired
    private CompanyVoMapper companyVoMapper;

    @Autowired
    private FileService fileService;

    @Autowired
    SecurityUtil securityUtil;

    @Autowired
    private DriverUserService driverUserService;

    @Autowired
    private RedisTemplateHelper redisTemplate;

    @Autowired
    CompanyUserService companyUserService;

    @Autowired
    UserService userService;

    @Override
    public IdCardDao getRepository() {
        return idCardDao;
    }



    @Override
    public Page<IdCard> findByCondition(IdCard idCard, SearchVo searchVo, Pageable pageable) {

        return idCardDao.findAll(new Specification<IdCard>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<IdCard> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {

                // TODO 可添加你的其他搜索过滤条件 默认已有创建时间过滤
                Path<Date> createTimeField = root.get("createTime");

                List<Predicate> list = new ArrayList<>();

                // 创建时间
                if (StrUtil.isNotBlank(searchVo.getStartDate()) && StrUtil.isNotBlank(searchVo.getEndDate())) {
                    Date start = DateUtil.parse(searchVo.getStartDate());
                    Date end = DateUtil.parse(searchVo.getEndDate());
                    list.add(cb.between(createTimeField, start, DateUtil.endOfDay(end)));
                }
                Predicate[] arr = new Predicate[list.size()];
                cq.where(list.toArray(arr));
                return null;
            }
        }, pageable);
    }

    @Override
    public PicFileVo upLoadIdCard(MultipartFile file, String fileConstant, Long userId) {
        User u = securityUtil.getCurrUser();
        PicFileVo res = new PicFileVo();
        if (!fileConstant.equals(FileConstant.IDCARD_HOID_PIC) && !fileConstant.equals(FileConstant.DRIVER_PIC)) {
            res = IdCardOCR(file, fileConstant);
        }
        File sfile = fileService.saveFileByUserId(file, fileConstant);
        res.setFileId(sfile.getId());
        res.setFilepath(sfile.getUrl());
        return res;
    }


    public PicFileVo IdCardOCR(MultipartFile file, String fileType) {
        PicFileVo res;
        try {
            java.io.File picFile = MyFileUtils.convert(file);
            String imgbase64 = FileUtils.baiud_img_file(picFile);
            picFile.delete();
            Map<String, Object> iDinfo = new HashMap<>();
            if (fileType.equals(FileConstant.IDCARD_BACK_PIC)) {
                iDinfo = IdCardOCRUtil.baiDuBackIdcard(imgbase64,redisTemplate);
                res = (IdCardBackVo) ObjectUtil.autoFillMapFields(iDinfo, IdCardBackVo.class);
            } else {
                iDinfo = IdCardOCRUtil.baiDuJustIdcard(imgbase64,redisTemplate);
                res = (IdCardFaceVo) ObjectUtil.autoFillMapFields(iDinfo, IdCardFaceVo.class);
            }
            if (!ObjectUtil.isAllFieldNotNull(res)) {
                throw new FreightException("图片不清晰： 请重新上传图片");
            }
        } catch (Exception e) {
            throw new FreightException(e.getMessage());
        }
        return res;
    }



    @Override
    public IdCard getIdCarDInfo(Long userId) {
        User u = userService.get(userId);

        Long idCardId = null;
        IdCard idCard = null;
        if (u.getUserType() == 0) {
            CompanyUser res = companyUserService.findByUserId(userId);
            if (res != null) {
                idCardId = res.getContactsIdCardId();
            }
        }
        if (u.getUserType()== 1) {
            DriverUser res = driverUserService.findByUserId(userId);
            if (res != null) {
                idCardId = res.getIdCardId();
            }
        }

        if (idCardId != null) {
            idCard = idCardDao.getOne(idCardId);
        }

        if(idCard == null){
            return new IdCard();
        }
        return idCard;
    }


}